import React, { useState } from 'react';
import { Input, Button, Checkbox, Modal, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000/'
import './RegisterPage.css';

const RegisterPage: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [agreeTerms, setAgreeTerms] = useState(false);
    const navigate = useNavigate();
    const [showTerms, setShowTerms] = useState(false);
    const [showPrivacy, setShowPrivacy] = useState(false);
    const [phone, setPhone] = useState('');
    const [smsCode, setSmsCode] = useState('');
    const [sentCode, setSentCode] = useState('');
    const [smsCountdown, setSmsCountdown] = useState(0);
    const [smsSending, setSmsSending] = useState(false);
    const [passwordStrength, setPasswordStrength] = useState({ level: 0, text: '', color: '' });

    // 用户名校验
    const isValidUsername = (name: string) => /^[a-zA-Z0-9_]{4,16}$/.test(name);
    // 密码校验
    const isValidPassword = (pwd: string) => /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+]{8,20}$/.test(pwd);
    // 手机号校验
    const isValidPhone = (num: string) => /^1[3-9]\d{9}$/.test(num);

    /**
     * 计算密码强度
     * @param pwd 密码字符串
     * @returns 密码强度对象，包含等级、文本描述和颜色
     */
    const calculatePasswordStrength = (pwd: string) => {
        if (!pwd) {
            return { level: 0, text: '', color: '' };
        }

        let score = 0;
        const checks = {
            length: pwd.length >= 8,
            lowercase: /[a-z]/.test(pwd),
            uppercase: /[A-Z]/.test(pwd),
            numbers: /\d/.test(pwd),
            symbols: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(pwd)
        };

        // 长度评分
        if (pwd.length >= 8) score += 20;
        if (pwd.length >= 12) score += 10;
        if (pwd.length >= 16) score += 10;

        // 字符类型评分
        if (checks.lowercase) score += 10;
        if (checks.uppercase) score += 10;
        if (checks.numbers) score += 15;
        if (checks.symbols) score += 15;

        // 复杂度评分
        const typeCount = Object.values(checks).filter(Boolean).length - 1; // 减去length
        if (typeCount >= 3) score += 10;
        if (typeCount >= 4) score += 10;

        // 确定强度等级
        let level, text, color;
        if (score < 30) {
            level = 1;
            text = '弱';
            color = '#ff4d4f';
        } else if (score < 60) {
            level = 2;
            text = '中等';
            color = '#faad14';
        } else if (score < 80) {
            level = 3;
            text = '强';
            color = '#52c41a';
        } else {
            level = 4;
            text = '很强';
            color = '#1890ff';
        }

        return { level, text, color };
    };

    /**
     * 处理密码输入变化
     * @param value 密码值
     */
    const handlePasswordChange = (value: string) => {
        setPassword(value);
        const strength = calculatePasswordStrength(value);
        setPasswordStrength(strength);
    };

    const MAX_ATTEMPTS = 3;
    const LOCK_TIME = 10 * 60 * 1000; // 10分钟

    const getRegisterAttempts = () => {
        const data = localStorage.getItem('register_attempts');
        return data ? JSON.parse(data) : { count: 0, lastFail: 0 };
    };

    const setRegisterAttempts = (count: number, lastFail: number) => {
        localStorage.setItem('register_attempts', JSON.stringify({ count, lastFail }));
    };

    // 发送验证码（前端模拟）
    const handleSendSms = () => {
        if (!isValidPhone(phone)) {
            message.error('请输入有效的手机号');
            return;
        }
        // 生成6位验证码
        const code = Math.floor(100000 + Math.random() * 900000).toString();
        setSentCode(code);
        setSmsCountdown(60);
        setSmsSending(true);
        message.success(`验证码已发送: ${code}`); // 实际开发中不应弹出验证码，仅用于演示
        // 倒计时
        const timer = setInterval(() => {
            setSmsCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(timer);
                    setSmsSending(false);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
    };

    const handleRegister = () => {
        // 1. 先判断是否被锁定
        const { count, lastFail } = getRegisterAttempts();
        const now = Date.now();
        if (count >= MAX_ATTEMPTS && now - lastFail < LOCK_TIME) {
            alert('注册失败次数过多，请10分钟后再试');
            return;
        }
        // 2. 前端格式校验
        if (!isValidUsername(username)) {
            alert('用户名格式不正确，需4-16位字母、数字或下划线');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (!isValidPassword(password)) {
            alert('密码格式不正确，需8-20位且包含字母和数字');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (!username || !password || !confirmPassword) {
            alert('请填写所有必填字段');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (!agreeTerms) {
            alert('请同意用户协议和隐私政策');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (!isValidPhone(phone)) {
            alert('请输入有效的手机号');
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        if (!smsCode || smsCode !== sentCode) {
            alert('短信验证码错误');
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        // 3. 模拟后端注册失败（如用户名已存在）
        if (username === 'test') {
            alert('该用户名已被注册');
            // 失败计数
            if (now - lastFail > LOCK_TIME) {
                setRegisterAttempts(1, now);
            } else {
                setRegisterAttempts(count + 1, now);
            }
            return;
        }
        // 4. 注册成功，清除失败记录
        localStorage.removeItem('register_attempts');
        console.log('注册成功', { username });
        alert('注册成功！即将跳转到登录页面');
        axios.post('login', {
            username,
            password
        }).then(res => {
            console.log(res)
        })
        navigate('/login');
    };

    return (
        <div className="register-container">
            {/* 右侧注册表单区域 */}
            <div className="register-form-container">
                {/* 公司Logo */}
                <div className="company-logo">
                    <div className="logo-icon"></div>
                    <span className="logo-text">Arco Pro</span>
                </div>

                {/* 注册表单 */}
                <div className="register-form">
                    <div className="input-group">
                        <Input
                            placeholder="用户名"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            className="register-input"
                        />
                    </div>

                    <div className="input-group">
                        <Input.Password
                            placeholder="密码"
                            value={password}
                            onChange={(e) => handlePasswordChange(e.target.value)}
                            className="register-input"
                        />
                        {password && (
                             <div className="password-strength" style={{ marginTop: '8px', fontSize: '12px' }}>
                                 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                                     <span style={{ color: passwordStrength.color, fontWeight: '500' }}>密码强度: {passwordStrength.text}</span>
                                     <span style={{ color: '#666', fontSize: '11px' }}>{passwordStrength.level}/4</span>
                                 </div>
                                 <div style={{ width: '100%', height: '4px', backgroundColor: '#f0f0f0', borderRadius: '2px', marginBottom: '8px' }}>
                                     <div style={{ width: `${(passwordStrength.level / 4) * 100}%`, height: '100%', backgroundColor: passwordStrength.color, borderRadius: '2px', transition: 'all 0.3s ease' }}></div>
                                 </div>
                                 <div style={{ color: '#666', fontSize: '11px', lineHeight: '1.4' }}>
                                     <div>密码要求:</div>
                                     <div style={{ marginTop: '2px' }}>
                                         <span style={{ color: password.length >= 8 ? '#52c41a' : '#ff4d4f' }}>• 至少8位字符</span>
                                         <span style={{ marginLeft: '12px', color: /[a-z]/.test(password) ? '#52c41a' : '#ff4d4f' }}>• 小写字母</span>
                                     </div>
                                     <div>
                                         <span style={{ color: /[A-Z]/.test(password) ? '#52c41a' : '#ff4d4f' }}>• 大写字母</span>
                                         <span style={{ marginLeft: '12px', color: /\d/.test(password) ? '#52c41a' : '#ff4d4f' }}>• 数字</span>
                                         <span style={{ marginLeft: '12px', color: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password) ? '#52c41a' : '#ff4d4f' }}>• 特殊字符</span>
                                     </div>
                                 </div>
                             </div>
                         )}
                    </div>

                    <div className="input-group">
                        <Input.Password
                            placeholder="确认密码"
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            className="register-input"
                        />
                    </div>

                    <div className="input-group">
                        <Input
                            placeholder="手机号"
                            value={phone}
                            onChange={e => setPhone(e.target.value)}
                            className="register-input"
                        />
                    </div>
                    <div className="input-group" style={{ display: 'flex', alignItems: 'center' }}>
                        <Input
                            placeholder="短信验证码"
                            value={smsCode}
                            onChange={e => setSmsCode(e.target.value)}
                            className="register-input"
                            style={{ flex: 1, marginRight: 8 }}
                        />
                        <Button
                            type="primary"
                            onClick={handleSendSms}
                            disabled={smsSending || !isValidPhone(phone)}
                            style={{ width: 120 }}
                        >
                            {smsSending ? `${smsCountdown}秒后重发` : '发送验证码'}
                        </Button>
                    </div>

                    {/* 同意条款 */}
                    <div className="terms-agreement">
                        <Checkbox
                            checked={agreeTerms}
                            onChange={(e) => setAgreeTerms(e.target.checked)}
                        >
                            我已阅读并同意
                            <a href="#" className="terms-link" onClick={(e) => { e.preventDefault(); setShowTerms(true); }}>用户协议</a>
                            和
                            <a href="#" className="terms-link" onClick={(e) => { e.preventDefault(); setShowPrivacy(true); }}>隐私政策</a>
                        </Checkbox>
                    </div>

                    {/* 注册按钮 */}
                    <Button
                        type="primary"
                        onClick={handleRegister}
                        className="register-button"
                        disabled={!agreeTerms}
                    >
                        立即注册
                    </Button>

                    {/* 返回登录链接 */}
                    <div className="login-link">
                        已有账号？<button onClick={() => navigate('/login')}>立即登录</button>
                    </div>
                </div>

                {/* 底部版权信息 */}
                <div className="copyright-info">
                    警告：本软件受中国专利与国际公约保护，未经授权擅自复制全部或部分内容，将接受法律的严厉惩罚！V.20230129
                </div>
            </div>
            {/* 用户协议弹窗 */}
            <Modal
                open={showTerms}
                title="用户协议"
                onCancel={() => setShowTerms(false)}
                footer={null}
                width={600}
            >
                <div style={{ maxHeight: 400, overflowY: 'auto', textAlign: 'left' }}>
                    <h3>一、总则</h3>
                    <p>1.1 本协议是用户与本平台之间关于注册、使用本平台服务所订立的协议。</p>
                    <h3>二、用户注册</h3>
                    <p>2.1 用户在注册时应当提供真实、准确、完整的个人信息。</p>
                    <h3>三、用户权利与义务</h3>
                    <p>3.1 用户有权使用本平台提供的各项服务。</p>
                    <p>3.2 用户不得利用本平台从事违法活动。</p>
                    <h3>四、其他</h3>
                    <p>4.1 本协议的解释权归本平台所有。</p>
                </div>
            </Modal>
            {/* 隐私政策弹窗 */}
            <Modal
                open={showPrivacy}
                title="隐私政策"
                onCancel={() => setShowPrivacy(false)}
                footer={null}
                width={600}
            >
                <div style={{ maxHeight: 400, overflowY: 'auto', textAlign: 'left' }}>
                    <h3>一、信息收集</h3>
                    <p>1.1 我们会收集您在注册、使用服务过程中主动提供的信息。</p>
                    <h3>二、信息使用</h3>
                    <p>2.1 我们会将您的信息用于为您提供服务、优化体验等目的。</p>
                    <h3>三、信息保护</h3>
                    <p>3.1 我们会采取合理的安全措施保护您的信息安全。</p>
                    <h3>四、用户权利</h3>
                    <p>4.1 您有权访问、更正、删除您的个人信息。</p>
                </div>
            </Modal>
        </div>
    );
};

export default RegisterPage;